//
//  TodoViewModel.swift
//  emasdemo
//
//  Created by alex on 2024/6/4.
//

import Foundation
import Combine

class TodoViewModel: ObservableObject {
    @Published var todos: [Todo] = []
        private var cancellables = Set<AnyCancellable>()
        private let serverUrl = ""
        
        func fetchTodos() {
            guard let url = URL(string: serverUrl + "/listTodo") else { return }
            
            
            // 创建请求
                var request = URLRequest(url: url)
                request.httpMethod = "GET"
                
                // 设置请求头
                request.addValue("application/json", forHTTPHeaderField: "Content-Type")
                
    
            // 创建URLSession数据任务
                let task = URLSession.shared.dataTask(with: request) { data, response, error in
                    // 检查是否有错误
                    if let error = error {
                        print("Error: \(error.localizedDescription)")
                        return
                    }
                    
                    // 检查响应和数据是否有效
                    if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200, let data = data {
                        
                        // 处理数据
                        do {
                            let json = try JSONDecoder().decode(Response.self, from: data)
                            self.todos = json.data
                            print("Response JSON: \(json)")
                        } catch {
                            print("Error decoding JSON: \(error)")
                        }
                    } else {
                        print("Error: Invalid response or no data")
                    }
                }
                
                // 启动任务
                task.resume()
        }
}
